package com.huadao.cart_ccs.common;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UtilHelpers {

    private String TAG="UtilHelpers";

    //蠕动泵的流速
    private static float rate=10;
    private static final int coefficient=51;

    private static final UtilHelpers ourInstance = new UtilHelpers();

    //为防止X轴的日期数值太大,减去这个值.
    public static final long referenceTime=new Date().getTime();

    public static UtilHelpers getInstance() {
        return ourInstance;
    }

    private UtilHelpers() {
    }

    /**
     * 根据传入控件的坐标和用户的焦点坐标，判断是否隐藏键盘，如果点击的位置在控件内，则不隐藏键盘
     *
     * @param view
     *            控件view
     * @param event
     *            焦点位置
     * @return 是否隐藏
     */
    public static void hideKeyboard(MotionEvent event, View view,
                                    Activity activity) {
        try {
            if (view != null && view instanceof EditText) {
                int[] location = { 0, 0 };
                view.getLocationInWindow(location);
                int left = location[0], top = location[1], right = left
                        + view.getWidth(), bootom = top + view.getHeight();
                // 判断焦点位置坐标是否在空间内，如果位置在控件外，则隐藏键盘
                if (event.getRawX() < left || event.getRawX() > right
                        || event.getY() < top || event.getRawY() > bootom) {
                    // 隐藏键盘
                    IBinder token = view.getWindowToken();
                    InputMethodManager inputMethodManager = (InputMethodManager) activity
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(token,
                            InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //检测IP格式
    public static boolean validIp(String ip){
        String expression = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."

                + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."

                + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."

                + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";

        Pattern p=Pattern.compile(expression);
        Matcher m=p.matcher(ip);
        return m.matches();
    }

    //检测代理商编号格式
    public static boolean validAgentNumber(String agentNumber){
        String expression = "^(\\d{4})";

        Pattern p=Pattern.compile(expression);
        Matcher m=p.matcher(agentNumber);
        return m.matches();
    }

    public static boolean validNetMask(String netMask) {
        return validIp(netMask);
    }

    //根据转速和流量计算出时间,单位秒,
    public static double calculateTimeBySpeedFlow(int speed,int flow){
        double time=(double) flow/speed*coefficient;
        //四舍五入
//        return Math.round(time);
        return time;
    }

    //根据时间和流量计算出转速,
    public static int calculateSpeedByFlowTime(int flow, int time) {
        double speed=(double) flow/time*coefficient;
        //四舍五入
        return (int) Math.round(speed);
    }

    //根据时间和转速计算出流量,
    public static int calculateFlowBySpeedTime(int speed, double time) {
        double flow=(double)speed*time/coefficient;
        //四舍五入
        return (int) Math.round(flow);
    }

    public static String getTime(float value) {
        return TimeUtil.chart_sdf.format((long)value+referenceTime);
    }

    public static float getTime(Date date) {
        return date.getTime()-referenceTime;
    }

    public static int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static boolean isServiceRunning(Context context, String ServiceName){
        if (TextUtils.isEmpty(ServiceName)) {
            return false;
        }
        ActivityManager myManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList<ActivityManager.RunningServiceInfo>) myManager
                .getRunningServices(Integer.MAX_VALUE);
        for (int i = 0; i < runningService.size(); i++) {
            if (runningService.get(i).service.getClassName().equals(ServiceName)) {
                return true;
            }
        }
        return false;
    }

    //获取本机MAC值,没有获取到则返回null
    public static String getMAC(){
//        return "16:6b:9c:90:56:c9";
//        return "12:a4:be:a8:7b:82";
//        return "12:a4:be:a8:7b:83";
//        return "12:a4:be:a8:88:f6";
//        return "16:6b:9c:90:56:c9";
        try {
            List<NetworkInterface> all= Collections.list(NetworkInterface.getNetworkInterfaces());
            for(NetworkInterface nif:all){
                if(nif.getName().equalsIgnoreCase("wlan0")){
                    continue;
                }

                byte[] macBytes=nif.getHardwareAddress();
                if(macBytes==null){
                    return null;
                }

                StringBuilder res=new StringBuilder();
                for(byte b:macBytes){
                    res.append(String.format("%02x:",b));
                }

                if(res.length()>0){
                    res.deleteCharAt(res.length()-1);
                }
                return res.toString();
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return null;
    }

    //关机
    public static void shutDownSystem(){
        Process chperm;
        try {
            chperm=Runtime.getRuntime().exec("su");
            DataOutputStream os =
                    new DataOutputStream(chperm.getOutputStream());

            os.writeBytes("reboot -p\n");
            os.flush();

            chperm.waitFor();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //返回秒
    public static int calculateTimeByAirAmount(int changeAirAmount) {
        return changeAirAmount;
    }
}
